package leetcode;

import pojo.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 105. 从前序与中序遍历序列构造二叉树
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2022-12-27
 */
public class LeetCode105 {

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null || preorder.length != inorder.length) {
            return null;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return f1(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
    }

    public static TreeNode f1(int[] pre, int L1, int R1, int[] in, int L2, int R2, Map<Integer, Integer> map) {
        if(L1 > R1){
            return null;
        }
        TreeNode treeNode = new TreeNode();
        treeNode.val = pre[L1];
        if (L1 == R1) {
            return treeNode;
        }
        int cur = map.get(pre[L1]);
        treeNode.left = f1(pre, L1 + 1, L1 + cur - L2, in, L2, cur - 1, map);
        treeNode.right = f1(pre, L1 + cur - L2 + 1, R1, in, cur + 1, R2, map);
        return treeNode;
    }

    public static void main(String[] args) {
        int[] pre = {3,9,20,15,7};
        int[] in = {9,3,15,20,7};
        TreeNode treeNode = buildTree(pre, in);
        System.out.println(treeNode);
    }
}
